import Vue from 'vue'
import VueRouter from 'vue-router'

// import Login from '@/views/login/index.vue'

import auth from '@/utils/token'

import { Message } from 'element-ui'
// import Layout from '@/views/Layout.vue'

// import Home from '@/views/home'
// import Article from '@/views/article'
// import Publish from '@/views/publish'

const Login = () => import('@/views/login')
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home')
const Article = () => import('@/views/article')
const Publish = () => import('@/views/publish')

// 注册全局路由组件
Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '/', component: Home },
        { path: 'article', component: Article },
        { path: 'publish/:id?', component: Publish }
      ]
    }
  ]
})
// 导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  //      next()  放行    next('/login')  强制跳转
  const token = auth.getToken()
  // 非登录页且没有token，跳转到登录页
  if (to.path !== '/login' && !token) {
    // 登录过期提示
    Message.error('请先登录')
    // 跳转登录页
    return next('/login')
  }
  // 其他情况放行
  next()
})

// 导出路由实例（跟这一步无关）
export default router
